<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../StaticFiles/element-ui/element-ui.css">
  <link rel="stylesheet" href="../StaticFiles/nprogress/nprogress.min.css">
  <link rel="stylesheet" href="../styles/vue-page-common.css">
  <script src="../Scripts/vue.min.js"></script>
  <script src="../StaticFiles/element-ui/element-ui.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <script src="../Scripts/xlsx.full.min.js"></script>
  <script src="../Scripts/crypto-js.js"></script>
  <script src="../Scripts/secret.js"></script>
  <title>MES工序排产数据删除</title>
</head>

<body>
  <div id="app" v-cloak>
    <!-- 报表标题 -->
    <vue2-report-header :title="'MES工序排产数据删除'"></vue2-report-header>
    <div style="padding: 10px;">
      <el-form :inline="true" :disabled="formDisable">
        <el-form-item>
          <el-upload action="" :before-upload="orderImportBeforeUpload" :multiple="true" accept=".xls,.xlsx">
            <el-button slot="trigger" type="primary" size="small" icon="el-icon-upload">选择文件</el-button>
            <el-button type="danger" size="small" icon="el-icon-warning" @click="deleteData" :loading="loading">删除
            </el-button>
            <span style="color:red;font-weight:bold;margin-left: 10px;">内部系统，严禁上传涉密信息</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="containerStepPlanImportData" stripe border ref="containerStepPlanImportData" v-loading="loading"
        v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" height="700">
        <el-table-column type="index" width="80"></el-table-column>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="操作" width="70">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="校验结果" prop="islegel" width="140" sortable>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.islegel === 1" type="success">校验成功</el-tag>
            <el-tag v-else type="danger">校验失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="校验失败原因" prop="illegalreason">
          <template slot-scope="scope">
            <span style="color:red;font-weight:bold;" v-if="scope.row.islegel === 0">
              <i class="el-icon-warning"></i>
              {{scope.row.illegalreason}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="批次号" prop="containername" sortable></el-table-column>
        <el-table-column label="工序" prop="workflowstepname" sortable></el-table-column>
      </el-table>
    </div>
  </div>

  <script src="../Scripts/echarts/echarts-5.4.0.min.js"></script>
  <script type="module">
    import { getParams, getUserWhiteList } from '../Scripts/hooks/useCommonMethod.js'
    import Vue2ReportHeader from '../Scripts/components/Vue2ReportHeader.js';
    const app = new Vue({
      el: '#app',
      components: { Vue2ReportHeader },
      data: {
        loading: false,
        loadingText: '数据加载中...',
        formDisable: false,
        // excel模板表头
        excelTemplateHeader: { containername: '批次号', workflowstepname: '工序' },
        // 所导入的数据
        containerStepPlanImportData: []
      },
      methods: {
        // 导入文件加载后
        orderImportBeforeUpload(file) {
          let reader = new FileReader();
          reader.onload = e => {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, { type: 'array' });
            let first_sheet_name = workbook.SheetNames[0];
            let worksheet = workbook.Sheets[first_sheet_name];
            let content = XLSX.utils.sheet_to_json(worksheet, { raw: false, defval: null });
            if (content.length === 0) {
              return this.$message.error('所导入的excel文件为空');
            }
            // 检验excel模板是否缺少列
            if (this.hasExcelMissingColumn(content[0])) { return; }
            let returnData = [];
            for (const i of content) {
              let item = {
                containername: i["批次号"],
                workflowstepname: i["工序"],
                islegel: 1,//默认校验成功
                illegalreason: ''//默认失败原因为空
              }
              returnData.push(item);
            }
            this.containerStepPlanImportData = this.validateEachRowData(returnData);
          };
          reader.readAsArrayBuffer(file);
          return false;
        },
        // 检验excel模板是否缺少列
        hasExcelMissingColumn(data) {
          return Object.values(this.excelTemplateHeader).some(i => {
            if (!(i in data)) {
              this.$message.error(`所导入的excel文件缺少【${i}】列`);
              return true;
            }
          })
        },
        // 校验所导入excel数据
        validateEachRowData(returnData) {
          for (const i of returnData) {
            if (!i.containername) {
              i.islegel = 0;
              i.illegalreason = '批次号不能为空';
            }
            if (!i.workflowstepname) {
              i.islegel = 0;
              i.illegalreason = '工序名称不能为空';
            }
          }
          return returnData;
        },
        // 校验用户权限
        async validateUser() {
          if (!getParams('uid')) {
            this.formDisable = true;
            return this.$notify.error({ title: '错误', message: '缺少用户信息!', duration: 0 });
          }
          const employeeid = getParams("uid");
          // 获取用户权限白名单
          const pageurl = window.location.pathname.split('/')[3];
          const whiteList = await getUserWhiteList(pageurl, this.$message);
          if (whiteList.indexOf(employeeid) == -1) {
            this.formDisable = true;
            this.$message.error('当前用户无权使用该功能');
          }
        },
        // 移除所选行
        async handleDelete(index, row) {
          const confirmResult = await this.$confirm('删除该行数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }
          this.containerStepPlanImportData.splice(this.containerStepPlanImportData.indexOf(row), 1);
        },
        async deleteData() {
          const selection = this.$refs.containerStepPlanImportData.selection;
          if (selection.length == 0) { return this.$message.error('请选择要删除的数据'); }
          if (selection.some(i => i.islegel === 0)) { return this.$message.error('存在校验失败的数据，不能执行删除'); };

          const confirmResult = await this.$confirm(`确认要永久删除所选 ${selection.length} 条排产数据吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }

          this.loading = true;
          this.loadingText = '数据删除中...';
          const { data: { data, meta, total } } = await axios({
            method: 'POST',
            url: '../handler/report/DeleteContainerStepPlanData.ashx?action=deleteData',
            data: { type: 'deleteData', willBeDeletedData: selection }
          })
          this.loading = false;
          this.containerStepPlanImportData = [];
          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          } else {
            return this.$message.success('删除成功');
          }
        }
      },
      mounted() {
        this.validateUser();
      }
    })
  </script>
</body>

</html>